package edu.nf.exam.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 工具类：MyBatisUtil
 * 获取SqlSession对象 <- SqlSessionFactory <- 核心配置文件
 */
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null ;


    static {
        
        try {
            // 读取核心配置文件，获取SqlSessionFactory，进而获取SqlSession对象，从而执行SQL映射的SQL语句
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param autoCommit  是否自动提交JDBC事务
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit){
        // 这个方式是自动提交事务的
        return sqlSessionFactory.openSession(autoCommit);

    }
}
